package likou.jindian;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2021/01/14 10:42
 */
public class _10_02 {

    public List<List<String>> groupAnagrams2(String[] strs) {
        int len = strs.length;
        HashMap<String, List<String>> map = new HashMap<>(len);
        for (String str : strs) {
            int[] count = new int[26];
            int str_len = str.length();
            for (int i = 0; i < str_len; ++i)
                ++count[str.charAt(i) - 'a'];
            StringBuilder sb = new StringBuilder(100);
            for (int num : count)
                sb.append(num + '.');
            map.computeIfAbsent(sb.toString(), unused -> new LinkedList<>()).add(str);
        }
        return new ArrayList<>(map.values());
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        int[] hashM = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 91, 97};
        int[] p = new int[strs.length];//存hash
        int index = 0;//当前已经存入的res.size()
        List<List<String>> res = new ArrayList<>();
        if (strs.length == 0) {
            return res;
        }
        for (int i = 0; i < strs.length; i++) {
            int hash = 0;
            byte[] nowSb = strs[i].getBytes();
            for (int j = 0; j < nowSb.length; j++) {
                hash += nowSb[j] * hashM[nowSb[j] - 'a'];
            }
            int nowListI = -1;
            for (int j = 0; j < index; j++) {
                if (p[j] == hash && panduan(res.get(j).get(0), strs[i])) {
                    nowListI = j;
                    break;
                }
            }
            if (nowListI == -1) {
                List<String> nowListA = new ArrayList<>();
                nowListA.add(strs[i]);
                p[index++] = hash;
                res.add(new ArrayList<>(nowListA));
            } else {
                res.get(nowListI).add(strs[i]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(panduan("abcc","cbbc"));
    }
    private static boolean panduan(String a, String b) {
        if (a.length() != b.length()) {
            return false;
        }
        byte[] ab = a.getBytes();
        byte[] bb = b.getBytes();
        int res = 0;
        for (int i = 0; i < ab.length; i++) {
            res ^= ab[i];
            res ^= bb[i];
        }
        return res == 0;
    }
}
